<template>
  <el-dialog
    class="basic-dialog"
    :model-value="visible"
    title="添加域名"
    :width="400"
    :close-on-click-modal="!loading"
    :close-on-press-escape="!loading"
    :show-close="!loading"
    @closed="handleClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-position="top"
      require-asterisk-position="right"
      @submit.prevent
    >
      <el-form-item label="支持添加主域名" prop="domain">
        <el-input v-model="formData.domain" placeholder="请输入域名"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :loading="loading" type="primary" @click="handleSubmit">
        确定
      </el-button>
      <el-button :loading="loading" @click="emit('update:visible', false)"
        >取消</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'
import type { Ref } from 'vue'

import type { UserModel } from '@/apis/model/user'
import ToastUtils from '@/utils/toast'

interface IProps {
  visible: boolean
  record?: undefined | null
  loading?: boolean
}

interface IEmits {
  (event: 'update:visible', value: boolean): void
  (event: 'update:loading', value: boolean): void
  (event: 'reload'): void
}

const emit = defineEmits<IEmits>()
withDefaults(defineProps<IProps>(), {})

const user = inject<Ref<UserModel>>('user')

const formRef = ref<FormInstance>()
const formData = reactive({
  domain: ''
})
const formRules = reactive<{ domain: FormItemRule[] }>({
  domain: [
    { required: true, message: '请输入域名', trigger: 'blur' },
    {
      trigger: 'blur',
      validator(_, value) {
        if (value.length > 253) {
          return new Error('域名总长度不能超过253个字符')
        }

        if (value.includes('.')) {
          const split = value.split('.').filter(item => item) as string[]

          for (const item of split) {
            if (!domainSplitReg.test(item)) {
              return new Error(
                '每一级域名为字母、数字、“-”、“_”的组合且长度不能超过63字符'
              )
            }
          }
        }

        if (!domainReg.test(value)) {
          return new Error('域名格式错误')
        }
        return true
      }
    }
  ]
})

/**
 * 保存方法
 */
const handleSubmit = async () => {
  await formRef.value?.validate()
  emit('update:loading', true)
  addDomainApi({
    user_id: user?.value?.id,
    name: formData.domain
  })
    .then(() => {
      ToastUtils.success('添加成功')
      emit('reload')
      handleClosed()
    })
    .finally(() => {
      emit('update:loading', false)
    })
}

/**
 * @description dialog 打开事件
 */
const handleDialogOpen = () => {}

/**
 * @description dialog 关闭前事件
 */
const handleClosed = () => {
  emit('update:visible', false)
  emit('update:loading', false)
  formRef.value?.resetFields()
}
</script>

<style scoped></style>
